/*******************************************************************************
 * Package: com.hngtrust.iir.report.service.impl
 * Type:    ReportServiceImpl
 * Date:    2021/9/14 13:58
 *
 * Copyright (c) 2021 HUANENG GUICHENG TRUST CORP.,LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.hngtrust.iir.material.service.impl;


import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONConfig;
import cn.hutool.json.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.hngtrust.framework.util.JsonUtils;
import com.hngtrust.iir.elk.exception.ElkErrorType;
import com.hngtrust.iir.elk.exception.ElkException;
import com.hngtrust.iir.material.controller.dto.SavePrivateMaterialReqVO;
import com.hngtrust.iir.material.controller.dto.UpdateSelectMaterialReqVO;
import com.hngtrust.iir.material.entity.MaterialRight;
import com.hngtrust.iir.material.entity.PrivateMaterial;
import com.hngtrust.iir.material.service.MaterialRightService;
import com.hngtrust.iir.material.service.MaterialService;

import com.hngtrust.iir.util.ElkUtils;
import com.tiger.util.MyHttpClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.text.MessageFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 资料实现类
 *
 * @author Chaidd
 * @date 2021/11/09 4:10 下午
 */
@Service
@Slf4j
public class MaterialServiceImpl implements MaterialService {
    @Value("${elk.search.url:}")
    private String elkUrl;
    
    //文件路径
    @Value("${elk.search.filepath}")
    private String elkFilePath;
    
    @Value(("${elk.search.filename.means}"))
    private String fileName;

    @Value(("${elk.search.indexname.means}"))
    private String indexName;
    
   
    
    @Autowired
    private MaterialRightService materialRightService;
    
    @Override
    public void createPrivateMaterial(PrivateMaterial privateMaterial) {
        if (StringUtil.isEmpty(fileName) || StringUtil.isEmpty(elkFilePath)) {
            log.error("创建ELK文件文件名:{}或者文件路径:{}为空", fileName, elkFilePath);
            return;
        }
        String content = this.createContent(privateMaterial);
        String name = MessageFormat.format(fileName, DateUtil.format(new Date(), "yyyyMMdd"));
        createText(content,name);
    }
    
    private void createText(String content, String name) {
        if (StringUtil.isEmpty(name) || StringUtil.isEmpty(elkFilePath)) {
            log.error("生成文件失败文件路径elkFilePath:{}或者文件名fileName:{}为空", name, elkFilePath);
            return;
        }
    
        BufferedWriter out = null;
        try {
            //判断文件路径是否存在
            File pathFile = new File(elkFilePath);
            if (!pathFile.exists()) {
                boolean result = pathFile.mkdirs();
                if(!result){
                    log.error("生成ELK文件夹路径失败:{}",elkFilePath);
                    return;
                }
            }
        
            String relFilePath = elkFilePath + File.separator + name;
            File file = new File(relFilePath);
            if (!file.exists()) {
                boolean result = file.createNewFile();
                if(!result){
                    log.error("生成ELK文件创建文件失败:{}",relFilePath);
                    return;
                }
            }
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true), StandardCharsets.UTF_8));
            out.write(content);
            out.newLine();
           
        } catch (Exception e) {
            log.error("生成文件失败：{}", e);
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    log.error("文件流关闭异常:", e);
                }
            }
        }
    
        log.info("创建公司信息文件全路径："+ elkFilePath +"/"+name);
    }
    
    private String createContent(PrivateMaterial privateMaterial) {
        Map<String,Object> map = new HashMap<>();
        map.put("iir_mysql_id",privateMaterial.getId());
        map.put("iir_title",privateMaterial.getTitle());//资料标题
        map.put("iir_industry_name",privateMaterial.getIndustryCode());//行业代码
        map.put("iir_dept_name",privateMaterial.getPublishDeptName());//发布部门名
        map.put("iir_deptid",privateMaterial.getPublishDeptId());//发布部门id
        map.put("iir_parent_deptid",privateMaterial.getPublishParentDeptId());//发布部门父级id
        map.put("iir_material_type",privateMaterial.getMaterialType());//资料类型
        map.put("iir_publish_username",privateMaterial.getPublishUserName());//发布人名
        map.put("iir_publish_userid",privateMaterial.getPublishUserId());//发布人id
        map.put("iir_summary",privateMaterial.getSummary());//摘要
        map.put("iir_size",privateMaterial.getFileSize());//文件大小
        map.put("iir_dow_tag",privateMaterial.getDwonTag());//允许下载
        if (privateMaterial.getPublishTime() != null){
            map.put("iir_publishtime",privateMaterial.getPublishTime());
        }else {
            map.put("iir_publishtime",privateMaterial.getCreateTime().getTime());
        }
        map.put("iir_currenttime",privateMaterial.getCreateTime().getTime());
        map.put("iir_right_tag",privateMaterial.getRightTag());//权限标识
        if (privateMaterial.getRightTag() == 2){
            MaterialRight materialRight = new MaterialRight();
            materialRight.setReportId(privateMaterial.getId());
            List<Long> collect = materialRightService.queryList(materialRight).stream().map(r -> r.getUserId())
                    .collect(Collectors.toList());
            map.put("iir_tag_id",collect);
        }
        map.put("iir_file_path",privateMaterial.getPdfPath());
        map.put("iir_status",0);
        map.put("iir_user_id",privateMaterial.getCreateUserId());
        map.put("iir_comments",privateMaterial.getComments());
        if (privateMaterial.getPages() != null){
            map.put("iir_pages",privateMaterial.getPages());
        }else {
            map.put("iir_pages",0);
        }
        
        return JsonUtils.toJson(map);
    }
    
    public String getPrintSize(long size) {
        long rest = 0;
        if(size < 1024){
            return String.valueOf(size) + "B";
        }else{
            size /= 1024;
        }
        
        if(size < 1024){
            return String.valueOf(size) + "KB";
        }else{
            rest = size % 1024;
            size /= 1024;
        }
        
        if(size < 1024){
            size = size * 100;
            return String.valueOf((size / 100)) + "." + String.valueOf((rest * 100 / 1024 % 100)) + "MB";
        }else{
            size = size * 100 / 1024;
            return String.valueOf((size / 100)) + "." + String.valueOf((size % 100)) + "GB";
        }
    }

    @Override
    public void updateElkReport(SavePrivateMaterialReqVO report) {
        String url = getElkUpdateUrl(indexName);
            MaterialRight materialRight = new MaterialRight();
            materialRight.setReportId(report.getId());
            List<Long> collect = materialRightService.queryList(materialRight).stream().map(r -> r.getUserId())
                    .collect(Collectors.toList());

        MyHttpClient client = new MyHttpClient();
        JSONConfig config = new JSONConfig();
        config.setOrder(true);
        JSONObject params = new JSONObject(config);
        JSONObject source = new JSONObject();
        source.put("source","ctx._source.iir['iir_mysql_id'] = '"+report.getId()+"';ctx._source.iir['iir_publishtime'] = '"+report.getPublishTime()+"';" +
                            "ctx._source.iir['iir_right_tag'] = '"+report.getRightTag()+"';ctx._source.iir['iir_dow_tag'] = '"+report.getDwonTag()+"';" +
                            "ctx._source.iir['iir_title'] = '"+report.getTitle()+"';ctx._source.iir['iir_industry_name'] = '"+report.getIndustryCode()+"';" +
                            "ctx._source.iir['iir_dept_name'] = '"+report.getPublishDeptName()+"';ctx._source.iir['iir_deptid'] = '"+report.getPublishDeptId()+"';" +
                            "ctx._source.iir['iir_material_type'] = '"+report.getMaterialType()+"';ctx._source.iir['iir_summary'] = '"+report.getSummary()+"';" +
                            "ctx._source.iir['iir_parent_deptid'] = '"+report.getPublishParentDeptId()+"';ctx._source.iir['iir_publish_username'] = '"+report.getPublishUserName()+"';" +
                            "ctx._source.iir['iir_publish_userid'] = '"+report.getPublishUserId()+"';ctx._source.iir['iir_publish_username'] = '"+report.getPublishUserName()+"';" +
                            "ctx._source.iir['iir_tag_id'] = '"+collect+"';ctx._source.iir['iir_status'] = '0';");


        JSONObject m = new JSONObject();
        JSONObject f= new JSONObject();
        f.put("iir.iir_mysql_id",""+report.getId()+"");
        m.put(ElkUtils.ELK_GRAMMAR_MATCH_PHRASE,f);
        params.put("script",source);
        params.put("query",m);

        log.info("修改参数{}",params.toString());
        System.out.println(params);
        client.postJson(url,params);
    }

    @Override
    public void deleteUpdateElkReport(UpdateSelectMaterialReqVO vo) {
        String url = getElkUpdateUrl(indexName);

        MyHttpClient client = new MyHttpClient();
        JSONConfig config = new JSONConfig();
        config.setOrder(true);
        JSONObject params = new JSONObject(config);
        JSONObject source = new JSONObject();
        source.put("source","ctx._source.iir['iir_status'] = '1';");
        JSONObject m = new JSONObject();
        JSONObject f= new JSONObject();
        f.put("iir.iir_mysql_id",""+vo.getId()+"");
        m.put(ElkUtils.ELK_GRAMMAR_MATCH_PHRASE,f);
        params.put("script",source);
        params.put("query",m);

        log.info("修改假删除参数{}",params.toString());
        System.out.println(params);
        client.postJson(url,params);
    }

    //获取ELK修改url
    private String getElkUpdateUrl(String indexName) {
        String url = null;
        if (jodd.util.StringUtil.isBlank(elkUrl) || jodd.util.StringUtil.isBlank(indexName)) {
            throw new ElkException(ElkErrorType.ELK_URL_INDEX_BLANK, elkUrl, indexName);
        }
        if (elkUrl.endsWith("/") || elkUrl.endsWith("\\")) {
            url = elkUrl + indexName + "/_update_by_query";
        } else {
            url = elkUrl + "/" + indexName + "/_update_by_query";
        }
        return url;
    }

}
